package Controlador;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;


@ManagedBean
@SessionScoped
public class LoginBean {

	private String usuario="";
	private String clave="";
	
	
	public String getClave() {
		return clave;
	}
	public void setClave(String clave) {
		this.clave = clave;
	}
	public String getUsuario() {
		return usuario;
	}
	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}
	
	
	public String login(){
		System.out.println("Logeando..."+usuario+"  pass:   "+clave);
		try { 
			ExternalContext cntxt = FacesContext.getCurrentInstance().getExternalContext(); 
			HttpServletRequest req = (HttpServletRequest) cntxt.getRequest(); 
			req.logout();

			req.login(this.usuario, this.clave);			
			
			System.out.println("Recibido "+req.getUserPrincipal());
			
			if (req.isUserInRole("Administrador")) 
				return "menu-administracion";
			//return "/menu-administracion.xhtml?faces-redirect=true";
			else if (req.isUserInRole("Cliente")) 
				return "/menu-clientes.xhtml?faces-redirect=true";			
			
		} catch (Exception e) { 
			System.out.println("Usuario No encontrado"); 
		}
		return "/errorpg.xhtml?faces-redirect=true"; 
	
	}
	
	public String logout() {
		try {
			ExternalContext cntxt = FacesContext.getCurrentInstance().getExternalContext();
			HttpServletRequest req = (HttpServletRequest) cntxt.getRequest();
			req.logout();
			usuario = "";
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/home.xhtml?faces-redirect=true";
	}
	
	public String verUsuario(){
		if(usuario==""){
			return "noLogin";
		}
		return usuario;
		
	}
	
}
